﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using Universe.OneC.DomainModel;

namespace Universe.OneC.ConsoleSample
{
    static class Program
    {
        private static readonly string ConnectionString =
            @"File=""C:\Users\_\Documents\1C\DemoHRM\"";Usr=Администратор;Pwd=";

        
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // TestDataProcessor.Run();

            using (Adapter1C adapter = new Adapter1C(AdapterUsageMode.Connector))
            {
                DateTime start = DateTime.Now;
                InfoBase ib = new InfoBase(new ServerInfo(1, "localhost"));
                // ib.FileBase = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @"1C\DemoHRM-2.5.9.2");
                ib.FileBase = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), @"1C\DemoHRM");

                // ib.Name = "ЗиУП-2.5.7.2";



                ib.UserName = "Администратор";
                ib.Password = "";
                adapter.Open(ib);

                DumpInterval(ref start, "Connect to 1C information base");

                

                // TestLargeScript.Run(adapter);

                OneCMetadataReader mr = new OneCMetadataReader();
                MetaModel model = mr.Get_1C_Metadata(adapter, ib);

                DumpInterval(ref start, "Read IB configuration metadata");

                XmlDocument dump = MetaIO.Dump(model);

                DumpInterval(ref start, "Dump configuration to xml");

                using (FileStream fs = new FileStream(model.Name + "-" + model.Version + ".xml", FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
                // using(StreamWriter wr = new StreamWriter(fs, Encoding.GetEncoding(1251)))
                {
                    XmlTextWriter xw = new XmlTextWriter(fs, Encoding.GetEncoding(1251));
                    xw.Formatting = Formatting.Indented;

                    dump.Save(xw);

                    xw.Flush();
                }

                start = DateTime.Now;

                OneCReader reader1c = new OneCReader(adapter, model);
                List<MetaClass> catalogs =
                    new List<MetaClass>(model.Registry.Values)
                        .FindAll(catalog => catalog.GetGroup2() == MetaClassGroup.Catalog || catalog.GetGroup2() == MetaClassGroup.Document);

                catalogs.Sort((x,y) => -x.Name.CompareTo(y.Name));

                DateTime local = DateTime.Now;
                foreach (MetaClass catalog in catalogs)
                {
                    Dump1C result = reader1c.ReadDocumentOrCatalog(catalog);
                    DumpInterval(ref local, catalog.GetGroup2() + ": " + catalog.Name);

                    string[] names = catalog.FullName.Split('.');
                    names[0] = names[0] + "-" + catalog.Model.Version;
                    string file = string.Join("\\", names) + ".htm";
                    Directory.CreateDirectory(Path.GetDirectoryName(file));
                    using(FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
                    using(StreamWriter wr = new StreamWriter(fs, Encoding.GetEncoding(1251)))
                    {
                        Dump1CIO io = new Dump1CIO(wr);
                        wr.WriteLine(Dump1CIO.Styles);
                        io.WriteHtml(catalog, result);
                    }

                }

                DumpInterval(ref start, "Read all 1C Documents and Catalogs");
            }

        }

        public static void DumpInterval(ref DateTime date, string title)
        {
            DateTime end = DateTime.Now;
            double seconds = (end - date).TotalSeconds;
            if (seconds > 0.5)
                Console.ForegroundColor = ConsoleColor.Yellow;

            Console.WriteLine(title + ": " + new DateTime(0).AddSeconds(seconds).ToString("mm:ss.f"));
            Console.ForegroundColor = ConsoleColor.White;

            date = DateTime.Now;
        }
    }
}
